//https://leetcode.cn/problems/4sum/submissions/585298198/
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int n = nums.size();
        vector<int> next(n, 1);
        int prev = nums[n - 1];
        for (int i = n - 2; i >= 0; --i)
        {
            if (nums[i] == nums[i + 1])next[i] = next[i + 1] + 1;
            else prev = nums[i];
        }
        vector<vector<int>> ret;

        for (int i = 0; i < n - 3;)
        {
            for (int j = i + 1; j < n - 2;)
            {
                long long tmp = (long long)target - nums[i] - nums[j];
                int left = j + 1, right = n - 1;
                while (left < right)
                {
                    if (nums[left] + nums[right] < tmp)left++;
                    else if (nums[left] + nums[right] > tmp)right--;
                    else { ret.push_back({ nums[i],nums[j],nums[left],nums[right] }); left += next[left]; right -= next[right]; }
                }
                j += next[j];
            }
            i += next[i];
        }
        return ret;
    }
};